from pmapi import log
from pmapi import lock
from pmapi import utils
import sys
import os
import shutil
import platform
import json
import hashlib

PACKAGE_PATH = f"{utils.find_disk()}\\" + \
    "PEinjector\\package".replace('\\', os.sep)


def act_pkg(pkg_name: str) -> None:  # 执行删除软件包（仅在 PE 下）
    if platform.system() == 'Windows' and os.path.exists("X:\\PEinjector"):
        log.info("hot remove package")
        # TODO


def remove(pkg_name: str, wait_user: bool = False, force_remove: bool = False, **kwargs) -> int:
    lockn = lock.Lock("remove")  # 加锁
    log.info("remove"+" "+pkg_name)
    try:
        with open(PACKAGE_PATH+os.sep+pkg_name+os.sep+"manifest.json", "r", encoding="utf-8") as file:
            file_json = json.load(file)
    except:
        log.warn("lost manifest.json")
    else:
        if "remove_sys_package" in kwargs and hashlib.md5((kwargs["remove_sys_package"]+"PEinjector").encode()).hexdigest().lower() == "1d305d88465b3b335b538c89d5a3adbb":
            log.warn("enable allow remove system package.only for debug.")
        else:
            if "keywords" in file_json and "PEinjector" in file_json["keywords"]:
                log.err("you will remove a system package.failed.")
                lockn.remove()
                return 4
        if force_remove:
            log.warn("pass depences check")
        dep_list = []
        for i in os.listdir(PACKAGE_PATH):
            try:
                with open(PACKAGE_PATH+os.sep+i+os.sep+"manifest.json", "r", encoding="utf-8") as file:
                    file_json = json.load(file)
                if pkg_name in file_json["dependence"]:
                    dep_list.append(i)
            except:
                pass
        if len(dep_list) != 0:
            log.err("some packages depend on this package.")
            log.err("please remove them before you remove this package.")
            sys.stdout.write("Remove package list:\n")
            sys.stdout.write("\n".join(["    "+i for i in dep_list]))
            lockn.remove()
            return 5
    if pkg_name not in os.listdir(PACKAGE_PATH):  # 找不到要删除的包
        log.err("package \""+pkg_name+"\" not install")
        lockn.remove()
        return 1
    if wait_user:  # 询问用户输入
        user_input = input("Remove? [Y/n]")
        if user_input not in ("y", "Y", "a", "A", ""):
            sys.stdout.write("Abort.\n")
            lockn.remove()
            return 2

    # 已知shutil在删除 .git 时会出现权限问题
    # 当出现问题时尝试使用系统命令
    try:
        shutil.rmtree(PACKAGE_PATH+os.sep+pkg_name)
    except:  # 降级命令
        if platform.system() == "Windows":
            retr = os.system(
                "RMDIR /S /Q "+PACKAGE_PATH.replace("/", "\\")+os.sep+pkg_name+" >nul")
        else:
            retr = os.system(
                "rm -rf "+PACKAGE_PATH.replace("\\", "/")+os.sep+pkg_name+" >/dev/null")
        if retr != 0:
            lockn.remove()
            return 3

    lockn.remove()
    return 0
